/*-----------------------------------------------------------------------------
		   Licensed to the Apache Software Foundation (ASF) under one
           or more contributor license agreements.  See the NOTICE file
           distributed with this work for additional information
           regarding copyright ownership.  The ASF licenses this file
           to you under the Apache License, Version 2.0 (the
           "License"); you may not use this file except in compliance
           with the License.  You may obtain a copy of the License at

             http://www.apache.org/licenses/LICENSE-2.0

           Unless required by applicable law or agreed to in writing,
           software distributed under the License is distributed on an
           "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
           KIND, either express or implied.  See the License for the
           specific language governing permissions and limitations
           under the License.  
-----------------------------------------------------------------------------*/

package parser;

import org.apache.commons.io.FileUtils;

import data.CurrentTask;
import data.ReportGen;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

import javax.swing.JFileChooser;

/**
 * This class creates the worker threads and will start them after all the
 * files that will be analyzed are read in.
 * 
 * @author Kevin.J.Jalbert
 */
public class WorkManager implements Runnable{

	/**
	 * When the thread starts running it will begin to allocate resources and 
	 * start the process of analyzing the root folder.
	 */
	@Override
	public void run() {

		// Creating two Normalizer threads
		Thread normalizer1 = new Thread(new Normalizer("normalizer1"));
		Thread normalizer2 = new Thread(new Normalizer("normalizer2"));

		// Creating two Cyclolizer threads
		Thread cyclolizer1 = new Thread(new Cyclolizer("cyclolizer1"));
		Thread cyclolizer2 = new Thread(new Cyclolizer("cyclolizer2"));

		/*
		 * TODO Currently a file dialog appears here, this is done since the
		 * gui is not yet completed, eventually this would be delegated to the
		 * gui and at this point the root folder would be known.
		 */
		// A file chooser is made to specify the root folder to be used
		JFileChooser fc = new JFileChooser();
		fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int returnValue = fc.showDialog(fc,"Use Directory");

		// The root folder is selected and saved
		File rootFolder = fc.getSelectedFile();

		// If file chooser dialog was cancelled, then exit the program
		if (returnValue == JFileChooser.CANCEL_OPTION){
			System.exit(0); // TODO Change when gui is implemented
		}

		// Find source files and add them to currentTask's normalization queue
		findSourceFiles(rootFolder);

		long startTime = System.nanoTime();

		normalizer1.start();
		normalizer2.start();	
		cyclolizer1.start();
		cyclolizer2.start();

		// Wait for the threads to finish working
		try {
			normalizer1.join();
			normalizer2.join();
			cyclolizer1.join();
			cyclolizer2.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

		long endTime = System.nanoTime();

		// Get an instance of CurrentTask and add root folder
		ReportGen report = new ReportGen();
		report.setRootFolder(rootFolder);

		// Try to print the report using the data gathered
		try {
			report.printReport();
		} catch (IOException e) {
			e.printStackTrace();
		}

		System.out.println("Time taken: " + (endTime - startTime)/1000000 + "ms");
	}

	/**
	 * Find all the source files by recursively traversing down the root folder
	 * and making note of all the files that have the correct file extension 
	 * based on the available languages.
	 * 
	 * @param currentTask the current task instance
	 * @param rootFolder the root folder
	 */
	private void findSourceFiles(File rootFolder) {

		// Get an instance of CurrentTask and add root folder
		CurrentTask currentTask = CurrentTask.getInstance();

		/*
		 * TODO Have a check to see what programming languages are available
		 * and just use those instead of having it hardcoded.
		 */
		// Have the support extensions of the support languages
		String[] extensions = {"c", "h", "java"};

		// Using org.apache.commons.io.FileUtils recursively traverse the root folder 
		Collection files = FileUtils.listFiles(rootFolder, extensions, true);
		for (Iterator iterator = files.iterator(); iterator.hasNext();) {

			// Add found file to the normalization queue in currentTask
			File file = (File) iterator.next();
			currentTask.addFileToNormQueue(file);
			currentTask.totalBytes.addAndGet(file.length());
		}
	}
}